export interface Params {
	param: { [field: string]: any | [any, any]; };
	order: { [field: string]: 1 | -1 | 0 | true | false | 'true' | 'false' | 'TRUE' | 'FALSE' | 'True' | 'False' | 'asc' | 'desc' | 'ASC' | 'DESC'; };
}

export default function p2q(p: Params) {
	if (!p.param) {
		p.param = {};
	}
	if (!p.order) {
		p.order = {};
	}
	const criteria = ((param) => {
		const fields = Object.keys(param);
		return fields.reduce((q, field) => {
			const v = param[field];
			if (Array.isArray(v)) { // 区间查询
				q[field] = { $gte: v[0], $lte: v[1] }
			} else if (v === '') {
				q[field] = '';	// 筛选条件选择“空”时
			} else if (v === true || v === false) {
				q[field] = v;
			} else if (typeof v === 'string') {	// 模糊查询
				q[field] = {
					$regex: '.*' + v + '.*',
					$options: "i"
				};
			} else {
				q[field] = v;
			}
			return q;
		}, {} as { [field: string]: any; });
	})(p.param);
	const sort = ((order) => {
		const fields = Object.keys(order);
		return fields.reduce((q, field) => {
			const v = order[field];
			q[field] = (!v || v === 'false' || v === 'FALSE' || v === 'False' || v === 'desc') ? -1 : 1;
			return q;
		}, {} as { [field: string]: 1 | -1; });
	})(p.order);
	return {
		criteria,
		sort
	};
}
